var events=require('events');
var net=require('net');

var channel=new events();
channel.clients={};
channel.subscriptions={};

channel.on('join', function (id, client) {
    this.clients[id]=client;
    this.subscriptions= function (senderId, msg) {
        if(id!==senderId){
            this.clients[id].write(msg);
        }
    }

    this.on('broadcast',this.subscriptions[id]);
});

var server=net.createServer(function (client) {
    var id=client.removeAddress+':'+client.remotePort;
    client.on('connect', function () {
        channel.emit('join',id,client);
    });

    client.on('data', function (data) {
        data=data.toString();
        channel.emit('broadcast',id,data);
    });
}).listen(8888, function () {
    console.log('net port:8888');
});
